package com.ctvit.common;

import java.io.File;
import java.io.FileFilter;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ctvit.framework.service.BaseService;
import com.ctvit.struts.common.CommonFunc;


public class FilerollService extends BaseService {
	public FilerollService() {
	}
	/**
	 * 在本文件夹下查找
	 * 
	 * @param 	 *            String 文件名
	 * @return File[] 找到的文件
	 * @throws ParseException 
	 */
	public  File[] getFiles() throws ParseException {
		return doGetFiles("./");
	}

	/**
	 * 获取文件 可以根据正则表达式查找
	 * 
	 * @param dir
	 *            String 文件夹名称
	 * @param 	 *            String 查找文件名，可带*.?进行模糊查询
	 * @return File[] 找到的文件
	 * @throws ParseException 
	 */
	public  File[] doGetFiles(String dir) throws ParseException {

		System.out.println("111111111---------------------");
		// 开始的文件夹
//		File file = new File(dir);
		final Date startDate=new Date(DateTimeUtil.parseDate(CommonFunc.lastFileTime,"yyyy-MM-dd HH:mm:ss").getTime() - 60*1000);
//     查找最后轮询文件的时间的前1分种到当前时间的文件
		
		final Date endDate=new Date();
		FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				if (pathname.isFile()){
					String name=pathname.getName().substring(0,pathname.getName().lastIndexOf("."));
					if (name.length()==36&&(pathname.getName().endsWith("xml")||pathname.getName().endsWith("XML"))){
//						if (startDate != null && pathname.lastModified() < startDate.getTime()) {
//							return false;
//						}
//						if (endDate != null && pathname.lastModified() > endDate.getTime()) {
//							return false;
//						}
						return true;
					}
				}
				return false;
			}
		};
		System.out.println("filter==="+filter);
		System.out.println("dir======"+dir);
		File[] array = new File(dir).listFiles(filter);
		List list = new ArrayList();
		
		if(array==null) {
			return array;
		}
		if(array.length>0){
			String lastdate = DateTimeUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
			try {
				CommonFunc.setLastFileTime(lastdate);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			for (int i = 0; i < array.length; i++) {
				System.out.println("begin===================totalXML==="+array[i]);
				try{
					parsetotal(array[i]);
				}catch(Exception e){
					e.printStackTrace();
					list.add(array[i].getName());
				
				}
					
				
			}
			System.out.println("list.toString================"+list.toString());
			
		}

		
//		
		return array;
		
	}	
	
	
// 解析总XML
   private void parsetotal(File file) {
	  
	   SAXReader reader = new SAXReader();
//		File filepath = new File(file);
		Document document = null;
		File totalfile = file;
		try {
			document = reader.read(file);
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Element root = document.getRootElement();
		List<Element> childElements = root.elements();
//		System.out.println("child: " + childElements.size());
		
		for(int i=0;i<childElements.size();i++){
			Element child = childElements.get(i);
			List<Element> childlist = child.elements();
			String newmediaID = "";
//			首先获取新增字段newMediaId值 
			for(int j=0;j<childlist.size();j++){
				Element childobj = childlist.get(j);
				String name = childobj.getName();
				if(name.equals("newMediaId")){
					newmediaID = childobj.getStringValue();
					System.out.println("newmediaID===="+newmediaID);
					break;
				}
			}
//			然后获取节目信息
			for(int j=0;j<childlist.size();j++){
				Element childobj = childlist.get(j);
				String name = childobj.getName();
			
				if(name.equals("Content")){
					List<Element> childsublist = childobj.elements();
					HashMap map = new HashMap();
					String totalfilepath = "";
					String mp4isnull = "0";
					String fileName ="";
					for(int k=childsublist.size()-1;k>=0;k--){
//					    String procode = null;
						Element subchild = childsublist.get(k);
						fileName = subchild.attributeValue("strName");
						int ll_index = fileName.lastIndexOf(".");
						if(fileName.equals("")||ll_index==-1) {
						  continue;	
						}
						System.out.println("parsetotal-------fileName-------------"+fileName);
						String prefix="";
						try{
							prefix=fileName.substring(fileName.lastIndexOf("."));
						}catch(StringIndexOutOfBoundsException e){
							try {
							 File afile = file;	
							 String movepath=file.getPath().substring(0,file.getPath().lastIndexOf(File.separator)+1);
							 if (afile.renameTo(new java.io.File(movepath +File.separator+ "movefile-1"+File.separator + afile.getName()))) {
//									
									System.out.println("File is success to movefile-1!" +movepath +File.separator+ "movefile-1"+File.separator + afile.getName());
								} else {
									System.out.println("File is failed to movefile-1!"+afile.getName());
								}
//							
							} catch (Exception e1) {
								e1.printStackTrace();
							}
						}catch (Exception e){
							 //主XML文件格式不对
							
							e.printStackTrace();

						}

						
						if(prefix.toUpperCase().equals(".XML")){
							System.out.println("parsetotal-------XML-------------");
							Integer ll =fileName.toUpperCase().lastIndexOf("VHD-QCM.XML");
							Integer ll_vas = fileName.toUpperCase().lastIndexOf("VAS-QCM.XML");
							Integer ll_VHL = fileName.toUpperCase().lastIndexOf("VHL-QCM.XML");
							Integer ll_VHR = fileName.toUpperCase().lastIndexOf("VHR-QCM.XML");
							Integer ll_VSD = fileName.toUpperCase().lastIndexOf("VSD-QCM.XML");
							Integer ll_VAQ = fileName.toUpperCase().lastIndexOf("VAQ-QCM.XML");
							Integer ll_VAH = fileName.toUpperCase().lastIndexOf("VAH-QCM.XML");
							Integer ll_V4K = fileName.toUpperCase().lastIndexOf("V4K-QCM.XML");
							
					        System.out.println("parsetotal-------ll_VHD-------------"+ll);
							System.out.println("parsetotal-------ll_vas-------------"+ll_vas);
							System.out.println("parsetotal-------ll_VHL-------------"+ll_VHL);
							System.out.println("parsetotal-------ll_VHR-------------"+ll_VHR);
							System.out.println("parsetotal-------ll_VSD-------------"+ll_VSD);
							System.out.println("parsetotal-------ll_VAQ-------------"+ll_VAQ);
							System.out.println("parsetotal-------ll_VAH-------------"+ll_VAH);
							System.out.println("parsetotal-------ll_V4K-------------"+ll_V4K);
							
							
							if(ll>0||ll_vas>0||ll_VHL>0||ll_VHR>0||ll_VSD>0||ll_VAQ>0||ll_VAH>0||ll_V4K>0){
								System.out.println("parsetotal-------开始解析QCM文件-------------");
								String path = file.getPath();
								if(path!=null&&!path.equals("")){
									String filepath = null;
									filepath = path.substring(0,path.lastIndexOf(File.separator)+1);
									
									totalfilepath = filepath;
									
									filepath = filepath + fileName;
                                
                                    map = parseDXML(new File(filepath),file);
                                   
									System.out.println("fileName=============="+fileName);
									if(map!=null){
										System.out.println("parsetotal-------map-------------"+map.toString());
//										map.put("newmediaID", newmediaID);
									}
									
								}

							}
						}else if(prefix.toLowerCase().equals(".mp4")&&(map!=null)){
							mp4isnull = "1";
							System.out.println("parsetotal-------mp4-------------");
						}
					}
					
					try {
						
						System.out.println("parsetotal-------map.size-------------"+map);
						if(map.size()!=0){
							if(mp4isnull.equals("1")){
								map.put("newMediaId", newmediaID);
								doFindByProgInfo(map,fileName,"mp4",totalfile,totalfilepath);
							};
						}
						
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		
	}
   
//

//解析子XML   
  public HashMap  parseDXML(File file,File totalfile) {
	  System.out.println("file========== " + file.getPath());
	  System.out.println("totalfile========== " + totalfile.getPath());
//	  判断文件是否存在
	  if(!file.exists()) {
//		    找不到子XML					
	    try {
			 File afile = totalfile;	
			 String movepath=totalfile.getPath().substring(0,totalfile.getPath().lastIndexOf(File.separator)+1);
			 if (afile.renameTo(new java.io.File(movepath +File.separator+ "movefile-2"+File.separator + afile.getName()))) {
//						
					System.out.println("File is success to movefile-2!" +movepath +File.separator+ "movefile-2"+File.separator + afile.getName());
				} else {
					System.out.println("File is failed to movefile-2!"+afile.getName());
				}
//				
			} catch (Exception e1) {
				totalfile.setLastModified(System.currentTimeMillis());
				e1.printStackTrace();
			} 
			return null;
	  }
	  
	  HashMap map = new HashMap();
	  
	   SAXReader reader = new SAXReader();
//		File file1 = new File("E:\\mam4ch5\\0-P2016S00710005-ME1-00-5907-02-000-VHD-QCM.XML");
	   Document document = null;
	   try {
		document = reader.read(file);
	   }catch (DocumentException e) {
			// 如查解析子XML出错，将修改总XML文件的时间
		    totalfile.setLastModified(System.currentTimeMillis());

		    e.printStackTrace();
//			e.printStackTrace();
			return null;
		}
		Element root = document.getRootElement();
		List<Element> childElements = root.elements();
		System.out.println("child========== " + childElements.size());

		
		for(int i=0;i<childElements.size();i++){
			Element child = childElements.get(i);
			String proname = null;
			String length = null;
			String segSum = null;
			String segnum = null;
			String procode = null;
			String langCode = null;
			System.out.println("child.getName()========== " + child.getName());
			
			if(child.getName().equals("ProgramInfo")){
				System.out.println("ProgramInfo=======1=== ");
				
				List<Element> childlist = child.elements();
				for(int j=0;j<childlist.size();j++){
					Element childobj = childlist.get(j);
					String name = childobj.getName();
//					System.out.println("name"+name);
					if(name.equals("ProgramCode")){
						procode = childobj.getStringValue();
						System.out.println("-procode--1----"+procode);
						map.put("procode", procode);
					}else if(name.equals("ProgramName")){
						proname = childobj.getStringValue();
						map.put("proname", proname);
					}else if(name.equals("TotalLength")){
						length = childobj.getStringValue();
						length = length.replaceAll(":","");
						length = length.substring(0,6);
						map.put("length", length);
				
					}else if(name.equals("ProgSegmentSum")){
						segSum = childobj.getStringValue();
						map.put("segSum", segSum);
					
					}
				}
			}else if(child.getName().equals("SubtitleInfo")){
				List<Element> childlist = child.elements();
				for(int j=0;j<childlist.size();j++){
					Element childobj = childlist.get(j);
					String lang = childobj.getName();
					System.out.println("lang========"+lang);
					if(lang.equals("SubtitleLanguage")){
						List<Element> subchild = childobj.elements();
						for(int k=0;k<subchild.size();k++){
							Element subch = subchild.get(k);
							String langname = subch.getName();
							System.out.println("langname========"+langname);
							if(langname.equals("LangCode")){
								langCode =subch.getStringValue();
								map.put("langCode", langCode);
								System.out.println("langCode========"+langCode);
							}
						}
						
					}
				}
			}else if(child.getName().equals("ProgSegment")){
			
				System.out.println("ProgSegment===2======= ");
				
				List<Element> childlist = child.elements();
				for(int j=0;j<childlist.size();j++){
					Element childobj = childlist.get(j);
					String name = childobj.getName();
//					System.out.println("name===="+name);
					if(name.equals("ProgSegmentNumber")){
						segnum = childobj.getStringValue();
						map.put("segnum", segnum);
					}
				}
			}

		}
		 //置zppm_t_proginfo字段的值
        if(!map.isEmpty()){
        	System.out.println("map===3======= ");
        	map.put("totalfile", totalfile.getPath());
        	
//     	   try {
//     		  doFindByProgInfo(map,"","xml");
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
        	
        }
        
		return map;
	}
  //将时分秒转化秒计
    public  String hourToSeconds(String length){
    	String hour = null;
    	String min = null;
    	String second = null;
    	String seconds = null;
    	Integer sec = null;
    	
    	hour = length.substring(0,2);
    	min = length.substring(2,4);
    	second = length.substring(4,6);
 
    	sec = Integer.parseInt(hour)*3600 + Integer.parseInt(min)*60 + Integer.parseInt(second);
    	seconds = String.valueOf(sec); 

    	return seconds;
    }
    
    //得到频道代码，名称
    public  String getChanl(String procode){
    	String result = "";
    	String zsubjcd = null;
    	String sql = null;
	    System.out.println("getChanl-procode="+procode);
	    if(StringUtils.isEmpty(procode)) {
		    return "FileName is empty";
	    }
        if(procode.length() == 13){
        	zsubjcd = procode.substring(4, 9);
        }else if(procode.length() == 12){
        	zsubjcd = procode.substring(2, 3) + "0" + procode.substring(3, 6);
        }
        System.out.println("zsubjcd ============="+ zsubjcd);
        sql = "select b.z_chanl_name as codename,b.z_chanl_cd as id from zcdm_t_subj a,zcdm_t_chanl b where a.z_chanl_cd = b.z_chanl_cd and a.z_subj_cd = '"+zsubjcd+"'";
        
        List<Map<String,?>> list= genericDao.executeSql(sql);
        if(list!=null&&list.size()>0){
        	HashMap chanlMap = (HashMap)list.get(0);

	 		 JSONArray jsonArray = JSONArray.fromObject(chanlMap);
	 		result=CommonFunc.dealWithFirstChar(jsonArray.toString());
        }
    	return result;
    }

//	如果是XML修改z_isplayed的值
	public void doFindByProgInfo(HashMap map,String fileName, String format,File movefile,String totalfilepath) throws SQLException {
		 String procode = (String)map.get("procode");
		 String proname = (String)map.get("proname");
		 String length = (String)map.get("length");
		 String segSum = (String)map.get("segSum");
		 String segnum = (String)map.get("segnum");
		 String langCode = (String)map.get("langCode");
		 String totalfile = (String)map.get("totalfile");
		 String newmediaID = (String)map.get("newMediaId");
//		 System.out.println("totalfile====="+totalfile);
//		 System.out.println("newmediaID====="+newmediaID);
//		 System.out.println("procode=="+procode+"proname=="+proname+"length=="+length+"segSum=="+segSum+"segnum=="+segnum+"langCode=="+langCode);
//		 String findbyprocode;
//		 String findbyseg;
		 String sqlinfo=null;
		 String sqlseg = null;
		 
		 
//		 findbyprocode= "select z_procode,z_aud_ver,z_cap_ver,z_subj_cd,z_pgnam,z_prog_desc," +
//		 		"z_time_estm,z_Prodstat,z_Plystat,CREATE_TIMESTAMP,MODIFY_TIMESTAMP,z_isplayed,z_vedio_exists," +
//		 		"z_vedio_crttim,z_preview_exists,z_prog_segnum " +
//		 		"from zppm_t_proginfo where z_procode= '" + procode+"'";
//		 System.out.println("findbyprocode========"+findbyprocode);
//		 List<Map<String,?>> list= genericDao.executeSql(findbyprocode);
		 
//		 findbyseg = "select z_procode,z_progseg,z_segnum,z_vedio_file,z_vedio_crttim,CREATE_TIMESTAMP from zppm_t_seginfo where z_procode= '" + procode+"'";
//		 List<Map<String,?>> listseg= genericDao.executeSql(findbyseg);
		 
//		 if(format.equals("xml")){
//			 System.out.println("SQL=====xml===");
//			 
//			sqlinfo = "update zppm_t_proginfo set z_pgnam = '"+proname+"',z_time_estm='"+length+"', z_prog_segnum = '"+segSum+"',MODIFY_TIMESTAMP = now() WHERE z_procode= '" + procode+"' and z_aud_ver = '"+langCode+"'";	
//		    if(genericDao.updateBySqlStr(sqlinfo)==0){
//		    	sqlinfo ="insert into zppm_t_proginfo(z_procode, z_pgnam, z_time_estm, z_prog_segnum,CREATE_TIMESTAMP,z_aud_ver) values('"+procode+"','"+proname+"','"+length+"','"+segSum+"',now(),'"+langCode+"')";
//		    	genericDao.updateBySqlStr(sqlinfo);
//		    }
//		 }
		 
		 if(format.equals("mp4")){
/////////////////////////////////////生成JSION  begin///////////////////////////////////////////////////
		     String ret = null;
			 HashMap mapj = new HashMap();
			 String mapc = "";
			 Map mapm = new HashMap();
			 
//			 mapc.put("codename", "OTT01");
//			 mapc.put("id", "ott01");
//	         mapm.put("8M", fileName);
//	 		 JSONArray jsonArraymapc = JSONArray.fromObject(mapc);
//	 		 String jsonStringmapc=CommonFunc.dealWithFirstChar(jsonArraymapc.toString());
//	         List list = new ArrayList();
			 if(StringUtils.isEmpty(procode)){
				 return;
			 }
	         mapc = getChanl(procode);
//			 System.out.println("list.tostring===="+list.toString());
	         mapj.put("coretag", mapc);
	         length = hourToSeconds(length);
	         mapj.put("duration", length);
	         mapj.put("id", procode);
	         mapj.put("title", proname);
	         mapj.put("reserve1", segSum);
	         mapj.put("reserve2", segnum);
	         mapj.put("8M",fileName);
	         mapj.put("newMediaId", newmediaID);
	         String jsonString="";
	         String url = "http://10.111.155.1/CMSMOBILE/api/OttTagAppApiVideoAction";
	        
	 		 JSONArray jsonArray = JSONArray.fromObject(mapj);
	 		 jsonString=CommonFunc.dealWithFirstChar(jsonArray.toString());
	 		 if(jsonString!=null&&!jsonString.equals("")){
	 			jsonString = jsonString.replaceAll("\\\\\"","\"");
	 			jsonString = jsonString.replaceAll("\"\\[","\\[").replaceAll("\\]\"","\\]");
		     }
	 		 System.out.println("jsonStirng========="+jsonString);
	 		//调用url发布
	 		 ret = CommonFunc.postJsonTo(jsonString,url); 
	 		
//	 		 if(1==1){
	 		 if( ret.indexOf("\"ref\":\"0\"") >= 0){
	 			 //写节目信息
	 			sqlinfo = "update zppm_t_proginfo set z_pgnam = '"+proname+"',z_time_estm='"+length+"', z_prog_segnum = '"+segSum+"',MODIFY_TIMESTAMP = now() WHERE z_procode= '" + procode+"' and z_aud_ver = '"+langCode+"'";	
			    if(genericDao.updateBySqlStr(sqlinfo)==0){
			    	sqlinfo ="insert into zppm_t_proginfo(z_procode, z_pgnam, z_time_estm, z_prog_segnum,CREATE_TIMESTAMP,z_aud_ver) values('"+procode+"','"+proname+"','"+length+"','"+segSum+"',now(),'"+langCode+"')";
			    	genericDao.updateBySqlStr(sqlinfo);
			    }
			    //写视频文件名
	 			 sqlseg = "update zppm_t_seginfo set z_vedio_file = '"+fileName+"',z_vedio_crttim = now() where z_procode = '"+procode+"' and z_segnum = '"+segnum+"'";
				 if(genericDao.updateBySqlStr(sqlseg)==0){
					 sqlseg = "insert into zppm_t_seginfo(z_procode,z_progseg,z_segnum,z_vedio_file,z_vedio_crttim,CREATE_TIMESTAMP) values('"+procode+"','"+segSum+"','"+segnum+"','"+fileName+"',now(),now())";
					 genericDao.updateBySqlStr(sqlseg);	 
				 }
				 
				 //写入成功后移走
				 try {
					 File afile = movefile;	
					 
					 if (afile.renameTo(new java.io.File(totalfilepath +File.separator+ "movefile"+File.separator + afile.getName()))) {
//							
							System.out.println("File is success to move!" +totalfilepath +File.separator+ "movefile"+File.separator + afile.getName());
						} else {
							System.out.println("File is failed to move!"+afile.getName());
						}
//					
					} catch (Exception e) {
						e.printStackTrace();
					}

					System.out.println("end===success====================="+movefile.getName()); 
	 		 }else{
	 			File file = new File(totalfile);
	 			file.setLastModified(System.currentTimeMillis()); 
	 			System.out.println("end===post JSON failed====================="+movefile.getName());
	 			return;
	 		 }
	 		 
////////////////////////////////////////////////end ///////////////////////////////////////////////	
//			 sqlseg = "update zppm_t_seginfo set z_vedio_file = '"+fileName+"',z_vedio_crttim = now() where z_procode = '"+procode+"' and z_segnum = '"+segnum+"'";
//			 if(genericDao.updateBySqlStr(sqlseg)==0){
//				 sqlseg = "insert into zppm_t_seginfo(z_procode,z_progseg,z_segnum,z_vedio_file,z_vedio_crttim,CREATE_TIMESTAMP) values('"+procode+"','"+segSum+"','"+segnum+"','"+fileName+"',now(),now())";
//				 genericDao.updateBySqlStr(sqlseg);	 
//			 }
////			 sqlseg = "insert into zppm_t_seginfo(z_procode,z_progseg,z_segnum,z_vedio_file,z_vedio_crttim,CREATE_TIMESTAMP) values('"+procode+"','"+segSum+"','"+segnum+"','"+fileName+"',now(),now())";
//			
//			 
		 }
	}
		 
//		
		 
	     
		
	/**
	 * 测试
	 * 
	 * @param args
	 *            String[]
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException {
		FilerollService fi = new FilerollService();
		File[] files=fi.doGetFiles("d:\\mam4ch5");
//		File[] files=fi.doGetFiles("e:\\解析文件\\mam4ch5");
//		
//		File file1 = new File("E:\\mam4ch5\\F094246A-8BF5-4EFA-932A-519F4F95E080.xml");
//		fi.parsetotal(file1);
//		String ls_length;
//		ls_length = hourToSeconds("013010");
//		System.out.print(ls_length);
//        new FilerollService().getChanl("12C001001001");
		
	}
}
